﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TVGuide.Common;
using System.Text.RegularExpressions;
using TVGuide.DataAccess.Exceptions;
//using TVGuide.DataAccess.Repository;
using TVGuide.DataAccess;
using TVGuide.DataAccess.Common;
using TVGuide.DataAccess.Repository;

namespace TVGuide.Parser
{
    ///<summary>
    /// Parses TV program information from UCOM. General URL for the schedule is http://ucom.am/hy/services/services-tv-channels.html?date=250
    /// </summary>

    public class UCOMParseEngine
    {
        private static string ucomHTMLString = "";
        private static bool useCachedHTML = false;
        /// <summary>
        ///     Parses specific program from UCOM.am site
        /// </summary>
        /// <param name="programName">Name of the program to parse</param>
        /// <param name="dayOfYear">Day of Year, to parse program for</param>
        /// <returns>List of programs. If there will be some issues while retrieving program list
        ///          it will send notification email, and return empty list, which will add no records in DB.
        /// </returns>
        public static List<Program> ParseSpecificProgram(Channel channel, DateTime date)
        {
            List<Program> tvProgramList = new List<Program>();
            string ucomURL = ChannelUrls.UCOM_URL + "?date=" + date.DayOfYear;
            if (!useCachedHTML)
            {
                ucomHTMLString = HTTPClient.GetSiteContent(ucomURL, Encoding.UTF8, "UcomSite");
                UCOMParseEngine.useCachedHTML = true;
            }

            string pattern = "<span class=\"desc\">" + Utils.EscapeSpacialSymbols(channel.Name) + "</span>.*?</div>";
            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
            Match matche = rgx.Match(ucomHTMLString);
            string capturedTable = matche.Value;
            string programDateStringPattern = "<p>\\d{2}:\\d{2}<br />";
            string programNameStringPattern = "<br />(.*?)</p>";
            Regex rgxProgramDateStrings = new Regex(programDateStringPattern);
            Regex rgxProgramNameStrings = new Regex(programNameStringPattern);
            MatchCollection programDates = rgxProgramDateStrings.Matches(capturedTable);
            MatchCollection programNamesWithTags = rgxProgramNameStrings.Matches(capturedTable);
            if (programDates.Count==0)
            {
                //TVGuide.Common.Utils.SendNotificationMail("Empty program list for " + channel.Name + " program parsed from UCOM.am for the "+date.Date+" date.");
                return tvProgramList;
            }
           
 
            int hour;
            int minute;
            for (int i = 0; i < programDates.Count; i++)
            {
                Utils.seperateTimeProgramName(programDates[i].Value, out hour, out minute);
                Program tvProgram = new Program();          
                tvProgram.Name = Utils.removeHTMLTags(programNamesWithTags[i].Value);
                tvProgram.Date = new DateTime(
                    date.Year,
                    date.Month,
                    date.Day,
                    hour,
                    minute,
                    0
                    );
                tvProgram.ChannelId = channel.Id;
                tvProgramList.Add(tvProgram);
            }

            return tvProgramList;
        }

        
        /// <summary>
        /// Parses specific program from UCOM.am site.
        /// </summary>
        /// <param name="programName">Name of the program to parse.</param>
        /// <returns></returns>
        public static List<Program> ParseSpecificProgram(Channel channel)
        {
            return ParseSpecificProgram(channel, DateTime.Today);
        }

        public static List<Program> ParseAll()
        {
            return ParseAll(DateTime.Today);
        }

        public static List<Program> ParseAll(DateTime date)
        {
            //TODO Remove debud stuff
            DateTime start = DateTime.Now;
            List<Program> allUCOMPrograms = new List<Program>();

            foreach (Enums.Channels value in Enum.GetValues(typeof(Enums.Channels)))
            {
                Channel channel = new Channel();
                ChannelRepository chanRep = ChannelRepository.Instance();
                var id = (int)value;
                channel.Id = id;
                channel.Name = chanRep.Get(id).Name;
                if (chanRep.Get(id).Enabled>0)
                    allUCOMPrograms.AddRange(ParseSpecificProgram(channel,date));
    
            }

            DateTime end = DateTime.Now;
            Console.WriteLine("Parsing for the date "+date.Date+"\nParse time is "+(end.Second-start.Second)+" second");
            UCOMParseEngine.useCachedHTML = false;
            return allUCOMPrograms;
        }

        
    }
}
